package com.example.redismanual.dao.actionExamples.BitmapExamples;

import io.swagger.models.auth.In;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

public class ZeroOneMatrix {

    private ValueOperations<String,String> client;
    private int rowNum;
    private int colNum;

    public ZeroOneMatrix(ValueOperations<String,String> client,int rowNum,int colNum){
        this.client = client;
        this.rowNum = rowNum;
        this.colNum = colNum;
    }
    public String get_matrix_key(String matrixName){
        return "matrix::" + matrixName;
    }

    public int calculateIndex(int row, int col, int rowNum, int colNum) throws Exception {
        if(!(row <  rowNum)){
            throw new Exception("error");
        }
        if(!(col <  colNum)){
            throw new Exception("error");
        }
        return row*rowNum + col;
    }

    public void set(int row,int col,Boolean value) throws Exception {
        String key = get_matrix_key("matrix_test");
        long index = calculateIndex(row, col, this.rowNum, this.colNum);
        this.client.setBit(key,index,value);
    }

    public Boolean get(int row,int col) throws Exception {
        String key = get_matrix_key("matrix_test");
        long index = calculateIndex(row, col, this.rowNum, this.colNum);
        return this.client.getBit(key,index);
    }

    public void showMatrix() throws Exception {
        for (int i = 0; i < this.rowNum; i++) {
            List<Integer> tempArray = new ArrayList<>();
            for (int j = 0; j < this.colNum; j++) {
                Boolean result = get(i,j);
                if(result){
                    tempArray.add(1);
                }else {
                    tempArray.add(0);
                }
            }
            System.out.println(String.format("matrix[%d]:%s",i,tempArray));
        }
    }
}
